package sharedjplaylist.client.playlist;

import java.util.ArrayList;
import java.util.Date;

import sharedjplaylist.client.BaseComposite;
import sharedjplaylist.client.service.PlaylistService;
import sharedjplaylist.client.service.PlaylistServiceAsync;
import sharedjplaylist.client.utils.CheckError;
import sharedjplaylist.client.utils.Encrypter;
import sharedjplaylist.shared.model.Playlist;
import sharedjplaylist.shared.model.Tunelist;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DatePicker;

public class CreatePlaylist extends BaseComposite {

    private static CreatePlaylistUiBinder uiBinder = GWT
        .create(CreatePlaylistUiBinder.class);

    protected PlaylistServiceAsync playlistService = GWT.create(PlaylistService.class);

    static int COLUMN_ORDER = 0;
    static int COLUMN_TITLE_ARTIST_NAME = 1;
    static int COLUMN_COMMENT = 2;

    Playlist currentPlaylist = null;

    interface CreatePlaylistUiBinder extends UiBinder<Widget, CreatePlaylist> {
    }

    @UiField
    Button saveButton;

    @UiField
    TextBox djnameTextBox;

    @UiField
    TextBox eventnameTextBox;

    @UiField
    TextBox genreTextBox;

    @UiField
    TextBox dateTextBox;

    @UiField
    PasswordTextBox passwordTextBox;

    @UiField
    PasswordTextBox confirmPasswordTextBox;

    @UiField
    Button datePickerButton;

    @UiField
    TextArea commentTextArea;

    @UiField
    FlexTable tunelistTable;

    @UiField
    Button addButton;

    @UiField
    TextBox columnnumberTextBox;

    @UiField
    Button importButton;

    @UiField
    TextArea importTextArea;

    public CreatePlaylist() {
        initWidget(uiBinder.createAndBindUi(this));
        setButton();
        settunelistTable();
    }

    public CreatePlaylist(Playlist editPlaylist, String password){
        initWidget(uiBinder.createAndBindUi(this));
        currentPlaylist = editPlaylist;
        setButton();
        setPlaylist(password);
    }

    private void setPlaylist(String password){
        djnameTextBox.setText(currentPlaylist.getDJName());
        eventnameTextBox.setText(currentPlaylist.getEventName());
        genreTextBox.setText(currentPlaylist.getGenre());
        dateTextBox.setText(currentPlaylist.getDatetime());
        passwordTextBox.setText(password);
        confirmPasswordTextBox.setText(password);
        commentTextArea.setText(currentPlaylist.getComment());

        settunelistTable(currentPlaylist.getTunelist());
    }

    private void settunelistTable(ArrayList<Tunelist> tunelistList){
        int row = 0;

        tunelistTable.setText(row, COLUMN_TITLE_ARTIST_NAME, "Title/Artist");
        tunelistTable.setText(row, COLUMN_COMMENT, "Comment");

        row++;

        for(Tunelist tunelist:tunelistList){

            tunelistTable.setText(row, COLUMN_ORDER, String.valueOf(row));
            TextBox tune_artistTextBox = new TextBox();
            tune_artistTextBox.setText(tunelist.getTune_artist());
            tunelistTable.setWidget(row, COLUMN_TITLE_ARTIST_NAME, tune_artistTextBox);

            TextBox commentTextBox = new TextBox();
            commentTextBox.setText(tunelist.getComment());
            tunelistTable.setWidget(row, COLUMN_COMMENT, commentTextBox);

            row++;
        }

    }

    private void settunelistTable() {
        int row = 0;

        tunelistTable.setText(row, COLUMN_TITLE_ARTIST_NAME, "Title/Artist");
        tunelistTable.setText(row, COLUMN_COMMENT, "Comment");

        addColumn(20);
    }

    private void setButton() {
        saveButton.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                setSavePlaylist();

            }
        });

        datePickerButton.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                setDatePicker();
            }
        });

        addButton.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                setAddColumn();

            }
        });

        importButton.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                setimport();

            }
        });
    }

    protected void setSavePlaylist() {
        String djnameString = djnameTextBox.getText();
        String eventnameString = eventnameTextBox.getText();
        String genreString = genreTextBox.getText();
        String dateString = dateTextBox.getText();
        String passswordString = passwordTextBox.getText();
        String confirmPasswordString = confirmPasswordTextBox.getText();
        String commentString = commentTextArea.getText();

        errorString = CheckError.checkPlaylist(djnameString, eventnameString, dateString, passswordString, confirmPasswordString);

        if(errorString.isEmpty()){
            Playlist playlist = new Playlist();
            playlist.setDJName(djnameString);
            playlist.setEventName(eventnameString);
            playlist.setGenre(genreString);
            playlist.setDatetime(dateString);
            playlist.setPassword(Encrypter.getHash(passswordString, Encrypter.ALG_SHA256));
            playlist.setComment(commentString);
            playlist.setUpdateDate(new Date());

            if(currentPlaylist != null){
                playlist.setKey(currentPlaylist.getKey());
                playlist.setCreateDate(currentPlaylist.getCreateDate());
            }else{
                playlist.setCreateDate(new Date());
            }

            playlist.setTunelist(getTunelist());

            playlistService.setPlaylist(playlist, new AsyncCallback<Void>() {

                public void onSuccess(Void result) {
                    setInfoMessage("Playlistの作成/更新に成功しました。");
                    clearErrorMessage();
                }

                public void onFailure(Throwable caught) {
                    clearInfoMessage();
                    setErrorMessage("Playlistの作成/更新に失敗しました。");

                }
            });
        }else{
            clearInfoMessage();
            setErrorMessage(errorString);
        }
    }

    private ArrayList<Tunelist> getTunelist() {
        ArrayList<Tunelist> tunelistList = new ArrayList<Tunelist>();

        for(int i = 1;i < tunelistTable.getRowCount();i++){
            String order = tunelistTable.getText(i, COLUMN_ORDER);

            TextBox titleartistTextBox = (TextBox)tunelistTable.getWidget(i, COLUMN_TITLE_ARTIST_NAME);
            String titleartistString = titleartistTextBox.getText();

            TextBox commentTextBox = (TextBox) tunelistTable.getWidget(i, COLUMN_COMMENT);
            String commentString = commentTextBox.getText();

            if(titleartistString == null || titleartistString.isEmpty()){
                continue;
            }else{
                Tunelist tunelist = new Tunelist();
                tunelist.setOrder(Long.valueOf(order));
                tunelist.setTune_artist(titleartistString);
                tunelist.setComment(commentString);

                tunelistList.add(tunelist);
            }
        }
        return tunelistList;
    }

    protected void setimport() {
        String[] importlist = importTextArea.getText().split("\n");

        if(importlist == null || importlist.length == 0 || importlist[0].trim().length() == 0){
            clearInfoMessage();
            setErrorMessage("ImportPlaylistにデータがありません。");
        }else{
            setColumn(importlist);
            setClear();
        }
    }

    private void setColumn(String[] importlist) {
        tunelistTable.removeAllRows();
        int row = 0;

        tunelistTable.setText(row, COLUMN_TITLE_ARTIST_NAME, "Title/Artist");
        tunelistTable.setText(row, COLUMN_COMMENT, "Comment");

        row++;
        for(String importString:importlist){
            tunelistTable.setText(row, COLUMN_ORDER, String.valueOf(row));

            TextBox titleartistTextBox = new TextBox();
            titleartistTextBox.setText(importString);
            tunelistTable.setWidget(row, COLUMN_TITLE_ARTIST_NAME, titleartistTextBox);

            tunelistTable.setWidget(row, COLUMN_COMMENT, new TextBox());

            row++;
        }
    }

    protected void setAddColumn() {
        String columnNumberString = columnnumberTextBox.getText();
        int columnNumber = 0;
        try{
            columnNumber = Integer.parseInt(columnNumberString);
        }catch(NumberFormatException e){
            clearInfoMessage();
            setErrorMessage("列追加には数値のみ入力してください。");
            return;
        }

        if(columnNumber > 100){
            columnNumber = 100;
        }else if(columnNumber < 1){
            columnNumber = 0;
        }

        addColumn(columnNumber);

        setClear();
    }

    private void setClear() {
        clearInfoMessage();
        clearErrorMessage();
    }

    private void addColumn(int columnNumber) {
        int row = tunelistTable.getRowCount();

        for(int i = row;i < row + columnNumber;i++){
            tunelistTable.setText(i, COLUMN_ORDER, String.valueOf(i));
            tunelistTable.setWidget(i, COLUMN_TITLE_ARTIST_NAME, new TextBox());
            tunelistTable.setWidget(i, COLUMN_COMMENT, new TextBox());
        }
    }

    protected void setDatePicker() {
        new DatePickerDialog(datePickerButton).show();
    }

    private class DatePickerDialog extends DialogBox{

        public DatePickerDialog(Button datePickerButton){
            setText("Select Date");
            setAnimationEnabled(true);
            setGlassEnabled(true);

            HTMLPanel content = new HTMLPanel("");
            DatePicker datePicker = new DatePicker();

            datePicker.setValue(new Date(), true);


            datePicker.addValueChangeHandler(new ValueChangeHandler<Date>() {
                public void onValueChange(ValueChangeEvent<Date> event) {
                  Date date = event.getValue();
                  DateTimeFormat formatter = DateTimeFormat.getFormat("yyyy/MM/dd");
                  dateTextBox.setText(formatter.format(date));
                  DatePickerDialog.this.hide();
                }
              });

            content.add(datePicker);
            add(content);

            setPopupPosition(datePickerButton.getAbsoluteLeft(), datePickerButton.getAbsoluteTop());
        }
    }
}
